import {logger} from "@/main/log.js";
import {getLeagueClientCertificate} from "@/main/lcu/LcuCertificate.js";
import {createHttpProxy} from "@/main/proxy/LcuHttpProxy.js";
import store, {store_field_lcu_certificate} from "@/main/store/store.js";
import {sendMessageToAllWindow, startWebSocketService} from "@/main/lcu/LcuEventHandler.js";
import {createDynamicWindow} from "@/main/windowLoad.js";
import {app,BrowserWindow} from 'electron'
// import {throttle} from './throttle.js'


let last = 0;

function throttle(fn, obj, delay, ...args) {
    return function () {
        const now = Date.now();
        logger.debug('throttle', now, last, args)
        if (now - last > delay) {
            last = now;
            fn.apply(obj, args);
        }
    };
}


let timer;

function debounce(fn, obj, delay) {
    return function () {
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(obj, args);
        }, delay);
    };
}


class LcuServerManager {
    ws;
    httpProxyServer;
    token;
    port;
    proxyPort
    connectStatus;
    gamePhase;


    //初始化
    async init(isReConnect) {
        logger.debug("开始进行lcu服务初始化", isReConnect);
        await getLcuCertificateLoop().then(certificate => {
            logger.debug("certificate=>", certificate)
            this.token = certificate.token;
            this.port = certificate.port;
            store.set(`${store_field_lcu_certificate}.token`, certificate.token);
            store.set(`${store_field_lcu_certificate}.port`, certificate.port);

            process.env.LCU_PORT = certificate.port;
            process.env.LCU_TOKEN = certificate.token;
            logger.debug(`lcu 凭证获取成功:${certificate.token} ${certificate.port}`);
            return Promise.resolve();
        });

        if (isReConnect && this.httpProxyServer) {
            this.httpProxyServer.close();
        }
        createHttpProxy(isReConnect, this.proxyPort)
            .then(res => {
                const {server, proxyPort} = res;
                this.httpProxyServer = server;
                this.proxyPort = proxyPort;
                logger.debug(`http proxy 服务启动成功,port:${this.proxyPort}`)
            })
        //启动wss通信服务
        startWebSocketService((connectStatus) => {
                this.connectStatus = connectStatus;
                sendMessageToAllWindow('lcu-server/status/push', {
                    'connectStatus': connectStatus,
                })
            },
            () => {
                debounce(lcuServerManager.init, lcuServerManager, 5000)(true);
            }, (gamePhase) => {

                handleDynamicWindow(this.gamePhase,gamePhase);
                this.gamePhase = gamePhase;

            }).catch((err) => {
            logger.error(`wss服务异常:${err}`)
        })
    }
}

const getLcuCertificateLoop = () => {
    return new Promise(resolve => {
        loopGetCertificate(({port, token}) => {
            resolve({port, token});
        })
    });
}

const loopGetCertificate = (callBack) => {
    getLeagueClientCertificate()
        .then(res => {
            callBack(res);
        })
        .catch(err => {
            logger.warn(`获取客户端token失败`, err, "尝试进行定时任务");
            setTimeout(() => {
                loopGetCertificate(callBack);
            }, 1000)
        })

}


const lcuServerManager = new LcuServerManager();


function handleDynamicWindow(originPhase,currentPhase){
    //如果现在是英雄选择阶段 且之前不是英雄选择 那么打开窗口 做个兜底  如果有什么bug已经打开了动态窗口 那么将窗口提到前面
    if(currentPhase==='ChampSelect'&&originPhase!==currentPhase){
        const dynamicWindows= BrowserWindow.getAllWindows().filter(a=>{
            return a.customerId === 'dynamic-window'
        })
        if(dynamicWindows.length===0){
            createDynamicWindow();
        }else{
            dynamicWindows[0].focus();
        }
    }


}

export {
    lcuServerManager
}
